<template>
    <div id="box">
        <div id="search">
            <el-form :inline="true" :model="searchForm" class="demo-form-inline">
                <el-form-item label="角色名">
                    <el-input v-model="searchForm.searchParams.roleCh" placeholder="请输入角色名"></el-input>
                </el-form-item>
                <el-form-item label="权限标识">
                    <el-input v-model="searchForm.searchParams.roleEn" placeholder="请输入权限字符"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="onSearchSubmit">搜索</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div id="header-bth">
            <el-button type="primary" size="small" icon=el-icon-circle-plus-outline @click="showAddRole">新增
            </el-button>
        </div>
        <div id="role-table">
            <el-table
                    :data="tableData"
                    stripe
                    height="310"
                    style="width:100%">
                <el-table-column label="角色名" prop="roleCh">
                </el-table-column>

                <el-table-column label="权限标识" prop="roleEn">
                </el-table-column>

                <el-table-column label="描述" prop="comments">
                </el-table-column>

                <el-table-column label="创建时间" width="200px" prop="createTime">
                </el-table-column>

                <el-table-column label="操作" width="280px">
                    <template slot-scope="scope">
                        <el-button
                                icon="el-icon-edit"
                                size="mini"
                                @click="handleEdit(scope.$index, scope.row)">
                        </el-button>

                        <el-popconfirm title="确定删除吗？" @confirm="deleteRole(scope.$index, scope.row)">
                            <el-button
                                    slot="reference"
                                    size="mini"
                                    type="danger"
                                    icon="el-icon-delete">
                            </el-button>
                        </el-popconfirm>
                        <el-button
                                size="mini"
                                type="success"
                                @click="handleAuth(scope.$index, scope.row)">分配权限
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div id="nav-page">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="searchForm.page"
                    :page-sizes="pageSizes"
                    :page-size="searchForm.limit"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>
        <!--添加 编辑角色信息弹窗-->
        <el-dialog :title="dialogTitle" :visible.sync="addRoleFormVisible" width="50%" @close="clearInfo">
            <el-form :model="roleForm" ref="roleInfo" :rules="roleRules" label-width="90px" size="medium">
                <el-input v-model="roleForm.roleId" autocomplete="off" v-show="false"></el-input>
                <el-form-item label="角色名" prop="roleCh">
                    <el-input v-model="roleForm.roleCh" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="权限字符" prop="roleEn">
                    <el-input v-model="roleForm.roleEn" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="描述" prop="comments">
                    <el-input v-model="roleForm.comments" show-word-limit maxlength="100" type="textarea"
                              :autosize="{ minRows: 5, maxRows: 10 }" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="saveOrUpdate">确 定</el-button>
            </div>
        </el-dialog>
        <!--分配权限-->
        <el-dialog title="分配权限" :visible.sync="authTreeVisible" width="30%" @close="clearTree">
            <el-tree
                    ref="tree"
                    :data="treeData"
                    show-checkbox
                    accordion
                    node-key="id"
                    :default-checked-keys="defaultCheckedKeys"
                    :default-expand-all="false"
                    :props="defaultProps">
            </el-tree>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="addRolePermissions">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>


import {addOrEditRole, insertRolePermissions, removeRole, rolePage, rolePermissions} from "@/api/role";
import {authTreeData} from "@/api/auth";
import {listToTree} from "@/utils/treeUtil";

export default {
    name: "RoleView",
    data() {
        return {
            tableData: [],
            pageSizes: [5, 10, 15],
            total: 10,
            roleId: '',
            addRoleFormVisible: false,
            authTreeVisible: false,
            authTreeCheckedKeys: [],
            defaultCheckedKeys: [],
            dialogTitle: '',
            roleForm: {},
            searchForm: {
                searchParams: {
                    roleCh: '',
                    roleEn: ''
                },
                limit: 5,
                page: 1
            },
            roleRules: {
                roleCh: [{required: true, message: '请输入角色名', trigger: 'blur'}],
                roleEn: [{required: true, message: '请输入角色标识', trigger: 'blur'}]
            },
            defaultProps: {
                children: 'children',
                label: 'title'
            },
            /*权限树形结构数据*/
            treeData: [
                {
                    id: 1,
                    title: "系统管理",
                    children: [
                        {
                            id: 3,
                            title: '用户管理',
                            children: [
                                {
                                    id: 4,
                                    title: '添加用户'
                                },
                                {
                                    id: 5,
                                    title: '删除用户'
                                },
                                {
                                    id: 6,
                                    title: '修改用户'
                                },
                                {
                                    id: 7,
                                    title: '查询用户'
                                }
                            ]
                        },
                        {
                            id: 13,
                            title: '角色管理',
                            children: [
                                {
                                    id: 14,
                                    title: '添加角色'
                                },
                                {
                                    id: 15,
                                    title: '删除角色'
                                },
                                {
                                    id: 16,
                                    title: '修改角色'
                                },
                                {
                                    id: 17,
                                    title: '查询角色'
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    },
    methods: {
        // 编辑角色
        handleEdit(index, row) {
            this.dialogTitle = "编辑"
            this.addRoleFormVisible = true
            // 数据回显
            this.roleForm = row

        },
        // 删除角色
        deleteRole(index, row) {
            // 发送异步请求 根据角色id 删除角色信息
            removeRole(row.roleId).then(response=>{
                if (response.code==0){
                    this.$notify.success(response.message)
                    this.getRoleList()
                }
            })

        },
        saveOrUpdate() {
            this.$refs.roleInfo.validate(valid => {
                if (!valid) {
                    this.$message.warning("请输入必要数据")
                    return
                }
                //  发送异步请求   实现角色的添加或修改    roleId
                addOrEditRole(this.roleForm).then(response=>{
                    if (response.code==0){
                        this.addRoleFormVisible =false
                        this.$notify.success(response.message)
                        this.getRoleList()
                    }
                })
            })

        },
        /*分配权限*/
        async handleAuth(index, row) {
            // 显示权限分配弹出层
            this.authTreeVisible = true
            this.roleId = row.roleId
            // 发送异步请求 渲染 权限树形结构  {code,message,data:{}}
            let {data}  =  await authTreeData()
            this.treeData = listToTree(data.permissionList)
            // 根据角色id  回显当前角色的权限  isMenu = 2
            rolePermissions(row.roleId).then(response=>{
                if (response.code==0){
                    this.defaultCheckedKeys = response.data.permissionList
                }
            })


        },
        addRolePermissions() {
             let halfCheckedKeys = this.$refs.tree.getHalfCheckedKeys()  // [1,2,3]   半选
             let checkedKeys = this.$refs.tree.getCheckedKeys()  //  [4,5,6]         全选
            // 数组结构赋值
             let newKeys = [...halfCheckedKeys,...checkedKeys]   // [1,2,3,4,5,6]  <=  [...HalfCheckedKeys,...CheckedKeys]
             let rid = this.roleId;

             let rolePermissions = {
                 newKeys,rid
             }

             if (newKeys.length==0){
                 this.$message.warning("请至少选择一个权限")
                 return
             }

             // 发送请求修改角色权限
            insertRolePermissions(rolePermissions).then(response=>{
                if (response.code==0){
                    this.$notify.success(response.message)
                    this.authTreeVisible =false
                }
            })
        },
        //清空权限回显数据
        clearTree() {
            this.defaultCheckedKeys = []
        },
        // 搜索角色
        onSearchSubmit() {
            this.searchForm.page = 1
            this.getRoleList()
        },
        // 改变每页显示的条数触发
        handleSizeChange(val) {
            this.searchForm.limit = val;
            this.getRoleList()
        },
        // 改变页码触发
        handleCurrentChange(val) {
            this.searchForm.page = val;
            this.getRoleList()
        },
        // 显示弹出层
        showAddRole() {
            this.dialogTitle = "新增"
            this.addRoleFormVisible = true
        },
        //清空校验规则
        clearInfo() {
            this.roleForm = {}
            this.$refs.roleInfo.clearValidate()
        },
        // 加载角色列表
        getRoleList() {
            rolePage(this.searchForm).then(response=>{
                if (response.code==0){
                    this.total = response.data.total
                    this.tableData = response.data.tableData
                }
            })
        }

    },
    created() {
        // 查询角色列表
        this.getRoleList()
    }
}
</script>

<style scoped>

#box {
    width: 95%;
    margin: 5px auto 0;
}

#search {
    width: 100%;
    height: 50px;
    padding-bottom: 20px;
    margin-top: 10px;
    margin-bottom: 20px;
    border-bottom: 1px solid #eee;
}

#header-bth {
    margin-bottom: 25px;
}

.el-button {
    margin-left: 5px;
    margin-right: 5px;
}

#nav-page {
    margin-top: 15px;
    margin-bottom: 30px;
}
</style>